import sys
import os
from ccpm.constants import Constant
from ccpm.pmbase import PluginBase, PmUtil
from ccpm.glan import Lan


class RunPlugin(PluginBase):

    PLUGIN_INFO = dict(
        name="run",
        ver="v0.0.1",
        help="run for develop the package!"
    )

    def __init__(self):
        if not hasattr(self, "_inc"):
            self._inc = super().__init__(self.PLUGIN_INFO)
        return self._inc

    def parser_config(self, argparser):
        super().parser_config(argparser)
        argparser.add_argument("runtype",
                               help=Lan.p(self.name, "PARSER_DESC_RUNTYPE"),
                               default="dev")

    def run(self, argpars):
        super().run(argpars)
        runtype = getattr(argpars, "runtype") if (
            hasattr(argpars, "runtype")) else "dev"
        (issuc, pconf) = PmUtil.is_runable_package_projpath(os.getcwd())
        if (issuc):
            run_cmd = pconf.get("scripts").get(runtype)
            if (not run_cmd):
                self.err_break(
                    Lan.p(self.name, "ERR_NOTE_CONFIG_DEVTOOL", runtype))
            self.__run_cmd(run_cmd)

        else:
            self.err_break(Lan.p(self.name, "ERR_NOT_RUNABLE_PATH"))

    def __run_cmd(self, cmdstr):
        self.logger.info("run cmd:%s", cmdstr)
        os.chdir(os.getcwd())
        os.system(cmdstr)


__all__ = [
    "RunPlugin"
]
